package model;

import java.util.List;

import util.AppUtil;

import com.jfinal.plugin.activerecord.Model;
import constant.Msg;

public class Zan extends Model<Zan>{
	private static final long serialVersionUID = 1L;
	public static final Zan dao = new Zan();
	public static final String findSQL="select * from zan where user_id = ? and type_id = ? and type = ?";
	public static final String pageSql = "select count(*) as num from zan where user_id = ? and type=?;";
	public static final String selectSql = "select * from zan where user_id = ? and type=? limit ? , ?;";
	public String getZans(int userId,String type, String offset,String length) {
		try {
			List<Zan> zans=dao.find(selectSql,userId,type,offset,length);
			int num = dao.find(pageSql,userId,type).get(0).getInt("num");
			int len = Integer.parseInt(length);
			int page = num==0?0:num%len==0?num%len:num%len+1;
			return AppUtil.modelToJson(zans, page);
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	public String like(int userId,String type,String typeId){
		try {
			List<Zan> zan=dao.find(findSQL,userId,typeId,type);
			int size=zan.size();
			if (size==0) {
				dao.set("user_id", userId)
				.set("type", type)
				.set("type_id", typeId)
				.set("status", 1)
				.set("create_time", (int)System.currentTimeMillis()/1000)
				.save();
				return Msg.SUCCESS_EXECUTE;
			}else if(size==1){
				if(zan.get(0).getInt("status")==1){
					return Msg.ERROR_STAR_EXISTED;
				}else{
					zan.get(0).set("status", 1).update();
					return "{\"code\": 0,\"msg\": \"成功\",\"data\": true}";
				}
			}else {
				System.out.println("错误：找到两个点赞数据");
				return Msg.ERROR_UNKNOWN;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	public String cancel(int userId,String type,String typeId){
		try {
			List<Zan> zan=dao.find(findSQL,userId,typeId,type);
			int size=zan.size();
			if (size==0)
			{
				zan.get(0).set("status", 0).update();
				return "{\"code\": 0,\"msg\": \"成功\",\"data\": false}";
			}else {
				return Msg.ERROR_DELETE_UNEXISTED;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	public String checkstar(int userId, String type, String typeId){
		try{
			List<Zan> zan=dao.find(findSQL,userId,typeId,type);
			if(zan.size()==0){
				return "{\"code\": 0,\"msg\": \"成功\",\"data\": false}";
			}else if(zan.size()==1){
				return "{\"code\": 0,\"msg\": \"成功\",\"data\": true}";
			}else{
				System.out.println("错误：找到两个或以上点赞数据");
				return Msg.ERROR_UNKNOWN;
			}
		}catch(Exception e){
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
}
